$(function () {
  // 类型筛选
  $("#select-type .select-item").click(function () {
    const type = $(this).attr("data-index");
    $("#select-type .content").text($(this).text());
    $("#select-type .content").addClass("active");
    updateQueryParamAndRedirect("type", type);
  });
  // 行业筛选
  $("#select-collection .select-item").click(function () {
    const collection = $(this).attr("data-index");
    $("#select-collection .content").text($(this).text());
    $("#select-collection .content").addClass("active");
    updateQueryParamAndRedirect("collection", collection);
  });
  $("#content").on("click", ".media-wrap-video", function () {
    const url = $(this).attr("data-video-url");
    $(".preview-video").eq(0).addClass("preview-show");
    $(".preview-video video").eq(0).attr("src", url);
    $(".preview-video .content video").trigger("play");
  });

  $(document).ready(function () {
    // 获取URL参数
    function getUrlParam(paramName) {
      var reParam = new RegExp("(?:[?&]|&)" + paramName + "=([^&]+)", "i");
      var match = window.location.search.match(reParam);
      return match && match.length > 1 ? match[1] : null;
    }

    // 获取.select-item的文本
    function getTypeSelectItemText(dataIndex) {
      var $selectItem = $(
          '#select-type .select-item[data-index="' + dataIndex + '"]'
      );
      return $selectItem.length ? $selectItem.text() : null;
    }

    // 获取.select-item的文本
    function getCollectionSelectItemText(dataIndex) {
      var $selectItem = $(
          '#select-collection .select-item[data-index="' + dataIndex + '"]'
      );
      return $selectItem.length ? $selectItem.text() : null;
    }

    // 检查type参数
    var typeParam = getUrlParam("type");
    if (typeParam) {
      var typeText = getTypeSelectItemText(typeParam);
      if (typeText) {
        $("#select-type .content").text(typeText);
        $("#select-type .content").addClass("active");
      }
    }

    // 检查collection参数
    var collectionParam = getUrlParam("collection");
    if (collectionParam) {
      var collectionText = getCollectionSelectItemText(collectionParam);
      if (collectionText) {
        $("#select-collection .content").text(collectionText);
        $("#select-collection .content").addClass("active");
      }
    }

    function timestampToFormattedDate(timestamp) {
      // 创建一个新的 Date 对象
      var date = new Date(timestamp * 1000); // 注意：JavaScript 的 Date 对象需要毫秒级的时间戳，所以乘以 1000

      // 获取年、月、日
      var year = date.getFullYear();
      var month = date.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的，所以需要加 1
      var day = date.getDate();

      // 如果月份或日期小于 10，则在前面补零
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;

      // 返回格式化后的日期字符串
      return year + "/" + month + "/" + day;
    }

    var loading = false; // 防止同时加载多次的标志
    var page = 1; // 初始化页码
    var totalPages = 1; // 总页数
    var throttleTimeout; // 用于节流的定时器
    var collectionParam = getUrlParam("collection");
    var typeParam = getUrlParam("type");
    var params = {};
    if (collectionParam && collectionParam != 0) {
      params.collection = collectionParam;
    }
    if (typeParam && typeParam != 0) {
      params.type = typeParam;
    }
    function loadMoreData() {
      if (page > totalPages || loading) {
        $("#nomore").show();
        return; // 如果正在加载或已加载完所有数据，则直接返回
      }
      params.page = page;

      loading = true; // 设置正在加载标志
      $("#loading").show(); // 显示加载提示

      $.ajax({
        url: "/home/page/ajaxKnowledgeShare", // 服务器端 URL，根据实际情况修改
        type: "GET",
        data: params, // 传递当前页码给服务器
        success: function (response) {
          var res = JSON.parse(response);
          var data = res.data;
          totalPages = res.last_page;
          page = res.current_page + 1; // 更新当前页码
          // 将新数据追加到内容区域
          var html = "";
          $.each(data, function (index, item) {
            // TODO: 区分视频类型 还是 文章类型 下面true替换为字段判断
            if (1 == item.share_type_id) {
              html += `<a href="javascript:;" class="list-item video-item">`;
              html += `<div class="left media-wrap-video" data-video-url="${item.videoaddress}">`;
              html += `<img src="${item.coverimage}" alt="">`;
              html += `<img class="play" src="/home_assets/imgs/share/icon-play.png" alt="">`;
              html += `</div>`;
              html += `<div class="info-wrap">`;
              html += `<div class="title">${item.name}</div>`;
              html += `<p class="desc">${item.summary}</p>`;
              html += `<p class="set">所属合集：${item.sharecollection.collection_name}</p>`;
              html += `<div class="other-info">`;
              html += `<div class="date">`;
              html += `<img src="/home_assets/imgs/share/icon-date.png" alt="">`;
              html += `<span>${timestampToFormattedDate(
                  item.createtime
              )}</span>`;
              html += `</div>`;
              html += `<div class="view">`;
              html += `<img src="/home_assets/imgs/share/icon-eye.png" alt="">`;
              // TODO: 缺少字段 阅读数 下面1283需要替换为实际值 ${item.字段名}
              html += `<span>1283</span>`;
              html += `</div>`;
              html += `</div>`;
              html += `</div>`;
              html += `</a>`;
            } else {
              // TODO: 缺少文章链接字段 下面 href值 ./detail.html需要替换为实际值 ${item.字段名}
              html += `<a href="/home/page/knowledgesharedetail/id/${item.id}" class="list-item img-item" target="_blank">`;
              html += `<div class="top">`;
              html += `<img src="${item.coverimage}" alt="">`;
              html += `</div>`;
              html += `<div class="info-wrap">`;
              html += `<div class="title">${item.name}</div>`;
              html += `<div class="other-info">`;
              html += `<p class="set">所属合集：${item.sharecollection.collection_name}</p>`;
              html += `<div class="date">`;
              html += `<img src="/home_assets/imgs/share/icon-date.png" alt="">`;
              html += `<span>${timestampToFormattedDate(
                  item.createtime
              )}</span>`;
              html += `</div>`;
              html += `<div class="view">`;
              html += `<img src="/home_assets/imgs/share/icon-eye.png" alt="">`;
              // TODO: 缺少字段 阅读数 下面1283需要替换为实际值 ${item.字段名}
              html += `<span>1283</span>`;
              html += `</div>`;
              html += `</div>`;
              html += `</div>`;
              html += `</a>`;
            }
          });
          $("#content").append(html);
          loading = false; // 数据加载完成，重置加载标志
          $("#loading").hide(); // 隐藏加载提示
        },
        error: function () {
          loading = false; // 在出错时重置加载标志
          $("#loading").hide(); // 隐藏加载提示
          alert("加载数据出错！");
        },
      });
    }

    function throttledScrollHandler() {
      var scrollBottom = $(window).scrollTop() + $(window).height();
      var listWrapBottom =
          $(".list-wrap").offset().top + $(".list-wrap").outerHeight();
      // 当窗口滚动到底部与 listWrap 底部接近时，加载更多内容
      if (scrollBottom >= listWrapBottom - 100 && !loading) {
        if (!loading && !throttleTimeout) {
          // 设置节流定时器，确保在指定时间内只触发一次加载操作
          throttleTimeout = setTimeout(function () {
            loadMoreData(); // 执行加载数据函数
            throttleTimeout = null; // 重置节流定时器
          }, 200); // 200毫秒后再次触发，可以根据需求调整
        }
      }
    }

    loadMoreData();

    $(window).scroll(throttledScrollHandler);
  });
});
